package com.jic.finance.common.util;


import org.dozer.DozerBeanMapper;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author guohuayong
 * @date: 2020年01月10日
 */
public class BeanUtil {
    private BeanUtil() {
    }

    private static final DozerBeanMapper DOZER = newInstance();

    /**
     * 把source中的值复制到target
     */
    public static void copy(Object source, Object target) {
        if (null == source || null == target) {
            return;
        }
        DOZER.map(source, target);
    }

    /**
     * 把source中的值复制到target
     */
    public static <T> T copy(Object source, Class<T> target) {
        return null == source || null == target ? null : DOZER.map(source, target);
    }

    /**
     * Copy List集合时可用
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> copy(List<T> source) {
        return new ArrayList<T>(source.size()) {
            private static final long serialVersionUID = 1L;

            {
                for (T src : source) {
                    add((T) copy(src, src.getClass()));
                }
            }
        };
    }

    /**
     * Copy List集合时可用[重载]
     */
    public static <E> List<E> copy(List<?> source, Class<E> target) {
        return new ArrayList<E>(source.size()) {
            private static final long serialVersionUID = 1L;

            {
                for (Object src : source) {
                    add(copy(src, target));
                }
            }
        };
    }

    /**
     * Bean属性输出为Map
     */
    public static Map<String, Object> toMap(Object obj) {

        if (null == obj) {
            return null;
        }
        Map<String, Object> retMap = new LinkedHashMap<String, Object>();

        for (Class<?> clazz = obj.getClass(); !clazz.isAssignableFrom(Object.class); ) {
            for (Field field : clazz.getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    try {
                        field.setAccessible(true);
                        Object val = field.get(obj);
                        if (null != val) {
                            retMap.put(field.getName(), val);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }

        return retMap;
    }

    /**
     * 返回默认实例
     */
    public static DozerBeanMapper newInstance() {
        return new DozerBeanMapper();
    }

}
